/**
 * webpack.common.js
 */
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const pathResolve = require('./pathResolve');
const { merge } = require('webpack-merge');
const { DefinePlugin } = require('webpack');

// 引入dev、prod配置文件
const devConfig = require('./webpack.dev.js');
const prodConfig = require('./webpack.prod.js');

const commonConfig = {
  entry: './src/index.js',
  output: {
    filename: 'js/main.js',
    path: pathResolve('./dist')
  },
  resolve: {
    extensions: ['.js', '.json', '.jsx', '.vue', '.ts', '.css'],
    alias: {
      '@': pathResolve('./src'),
    }
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1
            }
          },
          'postcss-loader'
        ]
      },
      {
        test: /\.less$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 2
            }
          },
          'postcss-loader',
          'less-loader'
        ]
      },
      {
        test: /\.(png|gif|svg|jpe?g)$/,
        type: 'asset',
        generator: {
          filename: 'img/[name].[hash:4][ext]'
        },
        parser: {
          dataUrlCondition: {
            maxSize: 50 * 1024
          }

        }
      },
      {
        test: /\.(ttf|woff2?)$/,
        type: 'asset/resource',
        generator: {
          filename: 'font/[name].[hash:3][ext]'
        }
      },
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      },
      {
        test: /\.ts$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      },
      {
        test: /\.vue$/,
        exclude: /node_modules/,
        use: ['vue-loader']
      },
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      title: 'webpack5实战',
      template: './public/index.html'
    }),
    new DefinePlugin({
      BASE_URL: '"./"',
    }),
    new VueLoaderPlugin(),
  ]
}

module.exports = () => {
  const NODE_ENV = process.env.NODE_ENV;
  
  const config = NODE_ENV === 'production' ? prodConfig : devConfig;

  const mergeConfig = merge(commonConfig, config);

  return mergeConfig;
}